package com.example.tanhuanapp.server.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import com.example.tanhuanapp.controller.AliyunOssConfig;
import com.example.tanhuanapp.pojo.vo.PicUploadResult;
import com.example.tanhuanapp.server.PicUploadServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
 * @author IT空门_门主
 * @date 2024/1/11
 */

@Slf4j
@Service
public class PicUploadServerImpl  implements PicUploadServer {
    //允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".jpg", ".jpeg", ".bmp", ".png", ".gif"};
    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOssConfig aliyunOssConfig;


    /**
     * 上传图片
     * @param uploadFile
     * @return
     */
    @Override
    public PicUploadResult upload(MultipartFile uploadFile) {
        log.info("传入的路径:{}",uploadFile);
        PicUploadResult fileUploadResult = new PicUploadResult();
         //图片做校验,对后缀名进行校验
        boolean isLegal = false;
        for (String type: IMAGE_TYPE ){
            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)){
                isLegal =true;
                break;
            }
        }
        //为 false校验失败
        if(!isLegal){
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //文件新路径
        String filename = uploadFile.getOriginalFilename();
        log.info("文件名:{}",filename);
        String filePath =getFilePath(filename);
        log.info("文件路径:{}",filePath);
        //上传到阿里云
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(),filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return  fileUploadResult;
        }
        //上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunOssConfig.getUrlPrefix()+filePath);
        log.info("OSS文件路径:{}",this.aliyunOssConfig.getUrlPrefix()+filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     * 处理图片路径
     * @param filename
     * @return
     */
    private String getFilePath(String filename) {
        DateTime dateTime = new DateTime();
        //生成文件名
        return "images/"+ dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd")
                +System.currentTimeMillis()+ RandomUtils.nextInt(100,9999)+"."+StringUtils.substringAfterLast(filename,".");
    }
}
